package com.example.study.mqtt.controller;

import com.example.study.config.JsonResult;
import com.example.study.config.ServerConfig;
import com.example.study.mqtt.MQTTServer;
import com.example.study.mqtt.config.MQTTConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpEntity;
//import org.springframework.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Base64;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Api(description = "mqtt控制", value = "mqtt控制2.0")
@RestController
@RequestMapping(value = "/testPublish")
public class PublishController {
    @Autowired
    private ServerConfig serverConfig;
    @Resource
    private MQTTServer mqttserver;
    @Resource
    private MQTTConfig config;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${constant.host}")
    private String host;

    @ApiOperation(value = "发送消息", notes = "参数:主题 消息 级别")
    @PostMapping(value = "/testPublish")
    public String testPublish(String topic, String msg, int qos, String userId) {
        mqttserver.sendMQTTMessage(topic, msg, qos, userId);
        String data = "发送了一条主题是‘" + topic + "’，内容是:" + msg + "，消息级别 " + qos;
        log.info(data);
        return data;
    }

    /**
     * 订阅主题
     *
     * @param topic 主题
     * @param qos   消息级别
     * @return
     */
    @ApiOperation(value = "订阅主题", notes = "参数:主题 级别")
    @PostMapping(value = "/testSubscribe")
    public String testSubsribe(String topic, int qos, String userId) {
        mqttserver.init(topic, qos, userId);
        log.info("订阅主题'" + topic + "'成功");
        return "订阅主题'" + topic + "'成功";
    }

    @ApiOperation(value = "取消订阅主题", notes = "参数:主题 级别")
    @PostMapping(value = "/unionInit")
    public String unionInit(String topic, String userId) {
        mqttserver.unionInit(topic, userId);
        return "取消订阅主题'" + topic + "'成功";
    }

    //http://8.130.21.209:15672/api/bindings/%2F
    //Authorization:
    //Basic bHVmZWk6NjQxODAxOQ==
    //        String url = "https://8.130.21.209:8081/cum/test1";

    //查询“/”虚拟机下的主题  藉由此获知用户是否上线
    @ApiOperation(value = "查询“/”虚拟机下的主题  藉由此获知用户是否上线")
    @GetMapping(value = "/bindings")
    public JsonResult<Boolean> bindings(@ApiParam("用户id") @RequestParam String userId) {
        JsonResult<Boolean> result=new JsonResult<>();
        result.message=userId+": 离线";
        JsonResult<BindingBean[]> bindsData = getBindsData();
        for (BindingBean datum : bindsData.data) {
            if (userId.equals(getUserId(datum.getDestination()))){
                result.data=true;
                result.message=userId+": 在线";
            }
        }
        return result;
    }


    @ApiOperation(value = "连接rabbitmq")
    @GetMapping(value = "/connect")
    public JsonResult<String> connect(@ApiParam("用户id") @RequestParam String userId) {
        JsonResult<String> result = new JsonResult<>("连接成功");
        mqttserver.subsribeConnect(userId);
        return result;
    }

    private String getUserId(String destination) {
        Pattern pattern = Pattern.compile("mqtt-subscription-([0-9]+)");
        Matcher matcher = pattern.matcher(destination);
        String value = "";
        if (matcher.find()) {
            value = matcher.group(1);
        }
        return value;
    }

    private JsonResult<BindingBean[]> getBindsData() {
        JsonResult<BindingBean[]> result = new JsonResult<>();
        String url = "http://" + host + ":15672/api/bindings/%2F";
        String username = "lufei";
        String password = "6418019";

// 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// 创建 GET 请求
        HttpGet request = new HttpGet(url);

// 设置请求标头
        String basicAuth = username + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(basicAuth.getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);
        request.setHeader(HttpHeaders.ACCEPT, "application/json");
        request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.62");
        request.setHeader(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
//        request.setHeader(HttpHeaders.UPGRADE_INSECURE_REQUESTS, "1");
        request.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=0");
        request.setHeader(HttpHeaders.CONNECTION, "keep-alive");

        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(request);

            // 获取响应实体
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // 将响应实体转换为字符串
                String responseBody = EntityUtils.toString(entity);

                // 输出响应字符串
                System.out.println(responseBody);

                // 创建 ObjectMapper 实例
                ObjectMapper objectMapper = new ObjectMapper();

                try {
                    // 将 JSON 数据解析为 Binding 实体类数组
                    // 对解析得到的实体类进行操作
                    result.data = objectMapper.readValue(responseBody, BindingBean[].class);
                } catch (Exception e) {
                    e.printStackTrace();
                    result.message = "解析失败";
                    result.code = 101;
                }

            }
        } catch (IOException e) {
            result.message = "请求失败";
            result.code = 101;
            e.printStackTrace();
        } finally {
            try {
                // 关闭 HttpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}